package TOP101;

import com.sun.jmx.remote.internal.ArrayQueue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @Question BM26
 * @Date 2022/11/9 16:29
 * @Solution
 */
public class BM26 {
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        ArrayList<ArrayList<Integer> > ans = new ArrayList();
        if(root == null)
            //如果是空，则直接返回空数组
            return ans;
        //队列存储，进行层次遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            int s=queue.size();
            ArrayList<Integer> row = new ArrayList<>();
            for(int i=0;i<s;i++) {
                TreeNode cur = queue.poll();
                row.add(cur.val);
                if(cur.left!=null) {
                    queue.add(cur.left);
                }
                if(cur.right!=null) {
                    queue.add(cur.right);
                }
            }
            ans.add(row);
        }
        return ans;
    }
}
